//
//  LoginPerformanceTest.swift
//  CMB250716
//
//  Created by Trae AI on 2025/1/16.
//

import SwiftUI
import Foundation

/// 诊断结果状态
enum DiagnosticStatus {
    case normal
    case warning
    case critical
}

/// 诊断结果
struct DiagnosticResult {
    let testName: String
    let duration: TimeInterval
    let status: DiagnosticStatus
    let details: String
    let recommendation: String
}

/// 登录性能测试工具
/// 用于自动化测试登录界面的性能问题
class LoginPerformanceTest: ObservableObject {
    @Published var isRunning = false
    @Published var testResults: [String] = []
    
    /// 运行完整的性能诊断测试
    func runFullDiagnostic() {
        guard !isRunning else { return }
        
        isRunning = true
        testResults.removeAll()
        
        DispatchQueue.main.async {
            self.testResults.append("开始登录界面性能诊断...")
            self.testResults.append("测试时间: \(Date())")
            self.testResults.append("")
        }
        
        // 异步运行诊断
        DispatchQueue.global(qos: .userInitiated).async {
            let results = self.runPerformanceTests()
            
            DispatchQueue.main.async {
                self.processResults(results)
                self.isRunning = false
            }
        }
    }
    
    /// 运行性能测试
    private func runPerformanceTests() -> [DiagnosticResult] {
        var results: [DiagnosticResult] = []
        
        // 1. 测试输入防抖延迟
        let debounceDelay = TimeInterval(LoginUIConfig.textFieldDebounceDelay) / 1000.0
        let debounceTest = measureTime {
            Thread.sleep(forTimeInterval: debounceDelay)
        }
        results.append(DiagnosticResult(
            testName: "输入防抖延迟测试",
            duration: debounceTest,
            status: debounceTest > 0.5 ? .critical : (debounceTest > 0.3 ? .warning : .normal),
            details: "当前防抖延迟: \(LoginUIConfig.textFieldDebounceDelay)ms",
            recommendation: debounceTest > 0.3 ? "建议减少 LoginUIConfig.textFieldDebounceDelay 参数" : "防抖延迟正常"
        ))
        
        // 2. 测试动画性能
        let animationTest = measureTime {
            Thread.sleep(forTimeInterval: LoginUIConfig.textFieldAnimationDuration)
        }
        results.append(DiagnosticResult(
            testName: "焦点动画性能测试",
            duration: animationTest,
            status: animationTest > 0.5 ? .warning : .normal,
            details: "动画持续时间: \(String(format: "%.0f", animationTest * 1000))ms",
            recommendation: animationTest > 0.5 ? "建议优化动画性能" : "动画性能正常"
        ))
        
        // 3. 测试按钮反馈延迟
        let buttonTest = measureTime {
            Thread.sleep(forTimeInterval: LoginUIConfig.buttonFeedbackDelay)
        }
        results.append(DiagnosticResult(
            testName: "按钮反馈延迟测试",
            duration: buttonTest,
            status: buttonTest > 0.2 ? .warning : .normal,
            details: "按钮反馈延迟: \(String(format: "%.0f", buttonTest * 1000))ms",
            recommendation: buttonTest > 0.2 ? "建议减少 LoginUIConfig.buttonFeedbackDelay 参数" : "按钮反馈正常"
        ))
        
        // 4. 测试视图重绘性能
        let redrawTest = measureTime {
            // 模拟视图重绘操作
            for _ in 0..<100 {
                _ = UUID().uuidString
            }
        }
        results.append(DiagnosticResult(
            testName: "视图重绘性能测试",
            duration: redrawTest,
            status: redrawTest > 0.01 ? .warning : .normal,
            details: "重绘耗时: \(String(format: "%.2f", redrawTest * 1000))ms",
            recommendation: redrawTest > 0.01 ? "建议优化视图结构" : "重绘性能正常"
        ))
        
        // 5. 测试Timer调度延迟
        let timerTest = measureTime {
            let semaphore = DispatchSemaphore(value: 0)
            Timer.scheduledTimer(withTimeInterval: 0.01, repeats: false) { _ in
                semaphore.signal()
            }
            semaphore.wait()
        }
        results.append(DiagnosticResult(
            testName: "Timer调度性能测试",
            duration: timerTest,
            status: timerTest > 0.05 ? .warning : .normal,
            details: "Timer调度延迟: \(String(format: "%.2f", timerTest * 1000))ms",
            recommendation: timerTest > 0.05 ? "系统Timer调度存在延迟" : "Timer调度正常"
        ))
        
        return results
    }
    
    /// 测量代码执行时间
    private func measureTime(_ block: () -> Void) -> TimeInterval {
        let startTime = CFAbsoluteTimeGetCurrent()
        block()
        let endTime = CFAbsoluteTimeGetCurrent()
        return endTime - startTime
    }
    
    /// 处理诊断结果
    private func processResults(_ results: [DiagnosticResult]) {
        testResults.append("=== 诊断结果汇总 ===")
        testResults.append("")
        
        var criticalIssues: [DiagnosticResult] = []
        var warningIssues: [DiagnosticResult] = []
        var normalResults: [DiagnosticResult] = []
        
        // 分类结果
        for result in results {
            switch result.status {
            case .critical:
                criticalIssues.append(result)
            case .warning:
                warningIssues.append(result)
            case .normal:
                normalResults.append(result)
            }
        }
        
        // 显示严重问题
        if !criticalIssues.isEmpty {
            testResults.append("🔴 严重性能问题 (\(criticalIssues.count)个):")
            for issue in criticalIssues {
                testResults.append("  • \(issue.testName): \(String(format: "%.2f", issue.duration * 1000))ms")
                testResults.append("    问题: \(issue.details)")
                testResults.append("    建议: \(issue.recommendation)")
                testResults.append("")
            }
        }
        
        // 显示警告问题
        if !warningIssues.isEmpty {
            testResults.append("🟡 性能警告 (\(warningIssues.count)个):")
            for issue in warningIssues {
                testResults.append("  • \(issue.testName): \(String(format: "%.2f", issue.duration * 1000))ms")
                testResults.append("    问题: \(issue.details)")
                testResults.append("    建议: \(issue.recommendation)")
                testResults.append("")
            }
        }
        
        // 显示正常结果
        if !normalResults.isEmpty {
            testResults.append("✅ 正常性能 (\(normalResults.count)个):")
            for result in normalResults {
                testResults.append("  • \(result.testName): \(String(format: "%.2f", result.duration * 1000))ms")
            }
            testResults.append("")
        }
        
        // 生成总结和建议
        generateSummaryAndRecommendations(criticalIssues: criticalIssues, warningIssues: warningIssues)
    }
    
    /// 生成总结和优化建议
    private func generateSummaryAndRecommendations(criticalIssues: [DiagnosticResult], warningIssues: [DiagnosticResult]) {
        testResults.append("=== 诊断总结 ===")
        
        if criticalIssues.isEmpty && warningIssues.isEmpty {
            testResults.append("✅ 登录界面性能良好，未发现明显问题")
        } else {
            let totalIssues = criticalIssues.count + warningIssues.count
            testResults.append("⚠️ 发现 \(totalIssues) 个性能问题需要关注")
            
            if !criticalIssues.isEmpty {
                testResults.append("🔴 严重问题: \(criticalIssues.count) 个 - 需要立即优化")
            }
            
            if !warningIssues.isEmpty {
                testResults.append("🟡 警告问题: \(warningIssues.count) 个 - 建议优化")
            }
        }
        
        testResults.append("")
        testResults.append("=== 优化建议 ===")
        
        // 根据问题类型提供具体建议
        var recommendations = Set<String>()
        
        for issue in criticalIssues + warningIssues {
            if issue.testName.contains("防抖") {
                recommendations.insert("• 调整 LoginUIConfig.textFieldDebounceDelay 参数")
                recommendations.insert("• 考虑禁用 LoginUIConfig.enableTextFieldOptimization")
            }
            
            if issue.testName.contains("动画") {
                recommendations.insert("• 优化动画性能，减少复杂计算")
                recommendations.insert("• 调整 LoginUIConfig.focusAnimationDuration 参数")
            }
            
            if issue.testName.contains("触觉反馈") {
                recommendations.insert("• 考虑禁用 LoginUIConfig.enableHapticFeedback")
                recommendations.insert("• 调整 LoginUIConfig.buttonFeedbackDelay 参数")
            }
            
            if issue.testName.contains("重绘") {
                recommendations.insert("• 优化视图结构，减少不必要的重绘")
                recommendations.insert("• 使用 @State 和 @Binding 优化状态管理")
            }
        }
        
        if recommendations.isEmpty {
            testResults.append("当前配置已优化，无需额外调整")
        } else {
            for recommendation in recommendations.sorted() {
                testResults.append(recommendation)
            }
        }
        
        testResults.append("")
        testResults.append("诊断完成时间: \(Date())")
    }
    
    /// 导出诊断报告
    func exportReport() -> String {
        return testResults.joined(separator: "\n")
    }
}

/// 性能测试视图
struct LoginPerformanceTestView: View {
    @StateObject private var tester = LoginPerformanceTest()
    @Environment(\.dismiss) private var dismiss
    
    var body: some View {
        NavigationView {
            VStack(spacing: 20) {
                // 标题
                VStack(spacing: 8) {
                    Text("登录性能诊断工具")
                        .font(.title2)
                        .fontWeight(.bold)
                    
                    Text("自动检测登录界面的性能问题")
                        .font(.caption)
                        .foregroundColor(.secondary)
                }
                
                // 运行按钮
                Button(action: {
                    tester.runFullDiagnostic()
                }) {
                    HStack {
                        if tester.isRunning {
                            ProgressView()
                                .scaleEffect(0.8)
                        } else {
                            Image(systemName: "play.circle.fill")
                        }
                        
                        Text(tester.isRunning ? "诊断中..." : "开始诊断")
                    }
                    .frame(maxWidth: .infinity)
                    .padding()
                    .background(tester.isRunning ? Color.gray : Color.blue)
                    .foregroundColor(.white)
                    .cornerRadius(10)
                }
                .disabled(tester.isRunning)
                
                // 结果显示
                if !tester.testResults.isEmpty {
                    ScrollView {
                        VStack(alignment: .leading, spacing: 4) {
                            ForEach(Array(tester.testResults.enumerated()), id: \.offset) { index, result in
                                Text(result)
                                    .font(.system(.caption, design: .monospaced))
                                    .foregroundColor(getTextColor(for: result))
                                    .frame(maxWidth: .infinity, alignment: .leading)
                            }
                        }
                        .padding()
                    }
                    .background(Color(.systemGray6))
                    .cornerRadius(10)
                }
                
                Spacer()
            }
            .padding()
            .navigationTitle("性能诊断")
            .navigationBarTitleDisplayMode(.inline)
            .navigationBarBackButtonHidden(true)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("关闭") {
                        dismiss()
                    }
                }
                
                if !tester.testResults.isEmpty {
                    ToolbarItem(placement: .navigationBarTrailing) {
                        Button("导出") {
                            let report = tester.exportReport()
                            UIPasteboard.general.string = report
                        }
                    }
                }
            }
        }
    }
    
    private func getTextColor(for text: String) -> Color {
        if text.contains("🔴") || text.contains("严重") {
            return .red
        } else if text.contains("🟡") || text.contains("警告") {
            return .orange
        } else if text.contains("✅") || text.contains("正常") {
            return .green
        } else {
            return .primary
        }
    }
}